<?php
/**
 * ------------------------------------------------------------------------
 * JA Disqus Debate Echo plugin for Joomla 1.7.x
 * ------------------------------------------------------------------------
 * Copyright (C) 2004-2011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
 * @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
 * Author: J.O.O.M Solutions Co., Ltd
 * Websites: http://www.joomlart.com - http://www.joomlancers.com
 * ------------------------------------------------------------------------
 */

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.plugin.plugin' );



class plgContentJADisqus_debate_echo extends JPlugin
{
	var $_plgCode = "#{jacomment(.*?)}#i";
	var $_plgCodeDisable = "#{jacomment(\s*)disable}#i";
	
	var $_url = "";
	var $_path = "";
	var $_postid = "";
	
	//var $source = "both";
	var $provider = "intensedebate";
	var $_comments = array();
	var $_commentsID = array();

	function plgContentJADisqus_debate_echo( &$subject, $config )
	{
		parent::__construct( $subject, $config );

		$this->plugin = &JPluginHelper::getPlugin('content', 'jadisqus_debate_echo');
		//$this->plgParams = new JParameter($this->plugin->params);
		$this->plgParams =  new JRegistry;
		$this->plgParams->loadJSON($this->plugin->params);
		//$this->source   = $this->plgParams->get('source', 'both');
		$provider         = $this->plgParams->get('provider', 'intensedebate');
		switch($provider) 
		{
			case 'disqus': $provider = 'disqus'; break;
			case 'jskit': $provider = 'jskit'; break;
			case 'intensdebate': $provider = 'intensedebate'; break;
			default: $provider = 'intensedebate'; break;
		}
		$this->provider = $provider;
		$this->stylesheet ($this->plugin);
	}
	function onContentBeforeDisplay($context, &$article, &$params, $limitstart = 0)
	{
		if(!$this->isDetailPage()) {
			//it is not called from detail view
			$return = $this->getDisqusContent($context, $article, $params, $limitstart , "introtext");
			return $return;
		}
		return ;
	}
	function onContentPrepare($context, &$article, &$params, $limitstart = 0)
	{
	   if($this->isDetailPage()) {
			//it is not called from detail view
			$return = $this->getDisqusContent($context, $article, $params, $limitstart);
			return $return;
		}
		return ;
	}
	function getDisqusContent(  $context, &$article, &$params, $limitstart, $typeText = "text")
	{
	   $mainframe = JFactory::getApplication();
		global $option;
		static $count = 0;
		
		static $addedUrls = array();
		//$sectionid      = $article->sectionid;
		$check = true;
		if(!isset($article->catid)) {
			$article->catid = 0;
		}
		
		if (!isset($article->text) && empty($article->text)) {
                $article->text = "";
        }
		
		if(!isset($article->text))
		{
			$article->introtext = isset($article->fulltext)?$article->fulltext:isset($article->introtext)?$article->introtext:"";
		}
		$catid          = $article->catid ;
		$option 		= JRequest::getCmd('option');
		$view 			= JRequest::getCmd('view');
		$itemid 		= JRequest::getInt('Itemid');
		$id				= JRequest::getInt('id');
		//
		$plugin = $this->plugin;
		$plgParams = $this->plgParams;
		//
		if(!isset($article->id) || !$article->id) {
			return '';
		}
		//if ($this->source != 'both' && $this->source != $option) 
		//	$check = false;
		
		$display_on_home = (int) $plgParams->get('display_on_home', 1);
		if($view == 'featured' && $display_on_home != 1)
			$check = false;
			
		$display_on_list = (int) $plgParams->get('display_on_list', 1);
		if((($option == 'com_content' && $view != 'article' && $view != 'featured')) && $display_on_list != 1)
			$check = false;
	
		if($this->isDetailPage()) {
			//it is not called from detail view
			if($id && $id != $article->id) {
				$check = false;
			}
		}
		$tmp_text = isset($article->text)?$article->text:isset($article->introtext)?$article->introtext:"";
		if(isset($article->text))
		{
			if(preg_match($this->_plgCodeDisable, $tmp_text)) {
				$check = false;
			}
		}
		if (!$check) {
			$article->text = $this->removeCode($tmp_text);
			return;
		}
		
		$isComment = false;

		//GET PLUGIN CONFIG
		$mode   		= $plgParams->get('mode','id');
		
		if($this->isContentItem($article)) {
			$catids         = $plgParams->get('mode-automatic-catsid','');
		} 
		$tagmode        = $plgParams->get('tagmode',0);
		$display_comment_count  = $plgParams->get('display_comment_count',1);
		//
		$user 		    =& JFactory::getUser();
		$document       =& JFactory::getDocument();
		$this->document =& $document;
		
		//CHECK PAGE WAS SELECTED TO DISPLAY COMMENT FORM
		switch ($mode)
		{
			case 'disable':
				$article->text = $this->removeCode($article->text);
				return;
				break;
			case 'manual':
				if (!preg_match($this->_plgCode, $article->text)) {
					return;
				}
				break;
			case 'automatic':
			default:
				if (is_array($catids)){
					if($catids[0]==''){
						$categories[] = $catid;
					}else{
						$categories = $catids;
					}
				} elseif ($catids==''){
					$categories[] = $catid;
				} else {
					$categories[] = $catids;
				}
				if( !(in_array($catid,$categories) || preg_match($this->_plgCode, $article->text))) {
					return;
				}
				break;
		}
		//END OF CHECK
		$text = !empty($typeText)?$typeText:"text";
		$authorised = JAccess::getAuthorisedViewLevels(JFactory::getUser()->get('id'));
		if(!isset($article->catslug))
		{
		   $article->catslug = $article->catid.':'.$article->category_alias;
		}
		if (in_array($article->access, $authorised)){
			if($option == "com_content") {
				$this->_path = JRoute::_(ContentHelperRoute::getArticleRoute($article->slug, $article->catslug));
			} else {
				$this->_path = "#";
			}
			
		} else {
			$this->_path = JRoute::_("index.php?option=com_user&view=login");
		}
		
		if(!preg_match("/^\//", $this->_path)) {
			//convert to relative url
			$this->_path = JURI::root(true).'/'.$this->_path;
		}
		//convert to absolute url
		$this->_url = $this->getRootUrl().$this->_path;
		
		$this->_sefurl = $this->convertUrl($this->_path);
		$this->_sefpath = $this->convertUrl($this->_path, true);
		
		if(in_array($this->_url, $addedUrls)) {
			return ;
		}
		$addedUrls[] = $this->_url;
		
		if ($option == "com_content" && $view=='article') {
			$isComment = true;
		}
	
		$this->_postid = md5($this->_url);
		
		if (!$isComment and $display_comment_count==0){ 
			return;
		}
		
		$this->isComment = $isComment;
		
		$provider = $this->provider;
		$output = $this->loadLayout ($this->plugin, $provider);
		/**
		 * JS Loading Optimize
		 * create place holder for comment 
		 */
		$uniqueID = $this->_postid;
		$container = 'JaCommentContainer'.$uniqueID;
		$holder = 'JaCommentPlaceHolder'.$uniqueID;
		$store = &Plg_comment_storage::getInstance();
		$store->_comments[] = '<div id="'.$container.'">'.$output.'</div>';
		$store->_commentsID[] = $uniqueID;
		
		$output = '<div id="'.$holder.'"></div>';
		if(isset($article->$text)) {
			if ($mode == 'manual' || preg_match($this->_plgCode, $article->$text)) {
				$article->$text = preg_replace( $this->_plgCode, $output, $article->$text );
			} else {
				$article->$text .= $output;
			}
		}
		return ;
	}
	/**
	 *
	 * @return (string) - root url without last slashes
	 */
	function getRootUrl() {
		$url = str_replace(JURI::root(true), '', JURI::root());
		$url = preg_replace("/\/+$/", '', $url);
			
		return $url;
	}
	
	function isDetailPage() {
		$option 	= JRequest::getVar('option');
		$view 		= JRequest::getVar('view');
		//if its a detail page
		
		if (($option == 'com_content' && $view == 'article')) {
			return true;
		}
		
		return false;
	}
	
	function isContentItem($article) {
		return isset($article->xreference) ? true : false;
	}
	/**
	 * convert from normal format to sef format
	 *
	 * @param unknown_type $matches
	 * @return unknown
	 */
	function convertUrl($originalPath, $pathonly=false)
	{
		jimport( 'joomla.application.router' );
		// Get the router
		$router = new JRouterSite( array('mode' => JROUTER_MODE_SEF) );
	
		// Make sure that we have our router
		if (! $router) {
			if($pathonly)
				return $originalPath;
			else 
				return $this->getRootUrl().$originalPath;
		}
		
		/*if ( (strpos($originalPath, '&') !== 0 ) && (strpos($originalPath, 'index.php') !== 0) ) {
			if($pathonly)
				return $originalPath;
			else 
				return $this->getRootUrl().$originalPath;
		}*/
		
		// Build route
		$path = str_replace(JURI::root(true), '', $originalPath);
		$uri = &$router->build($path);
		
		$path = $uri->toString(array('path', 'query', 'fragment'));
		if(!preg_match("/^\/+/", $path)) {
			$path = "/{$path}";
		}
		
		//
		if($pathonly) {
			return $path;
		} else {
			$url = $this->getRootUrl();
			return $url.$path;
		}
	}

	function onAfterRender(){
	
		$store = &Plg_comment_storage::getInstance();
		$this->_comments = $store->_comments;
		$this->_commentsID = $store->_commentsID;
		
		$body = JResponse::getBody();
		$comments = $this->loadLayout($this->plugin, 'common');
		$countscript = "";
		$body = str_replace('</body>', $comments."\n</body>",$body);
		
		if($this->provider == 'disqus') {	
			$countscript = $this->loadLayout($this->plugin, 'disqus_count');
			$body = str_replace('</body>', $countscript."\n</body>",$body);
		}
		JResponse::setBody($body);
	}
	
	function removeCode($content)
	{
		return preg_replace( $this->_plgCode, '', $content );
	}
	
	function getLayoutPath($plugin, $layout = 'default')
	{
		$mainframe = JFactory::getApplication();

		// Build the template and base path for the layout
		$tPath = JPATH_BASE.DS.'templates'.DS.$mainframe->getTemplate().DS.'html'.DS.$plugin->name.DS.$layout.'.php';
		$bPath = JPATH_BASE.DS.'plugins'.DS.$plugin->type.DS.$plugin->name.DS.'tmpl'.DS.$layout.'.php';
	
		// If the template has a layout override use it
		if (file_exists($tPath)) {
			
			return $tPath;
			
		} elseif (file_exists($bPath)) {
			
			return $bPath;
			
		}
		return '';
	}

	function loadLayout ($plugin, $layout = 'default') {
		$layout_path = $this->getLayoutPath ($plugin, $layout);
		if ($layout_path) {
			ob_start();
			require $layout_path;
			$content = ob_get_contents();
			ob_end_clean();
			return $content;
		}
		return '';
	}

	function stylesheet ($plugin) {
		$mainframe = JFactory::getApplication();
		JHTML::stylesheet('plugins/'.$plugin->type.'/'.$plugin->name.'/'.'style.css');
		if (is_file(JPATH_SITE.DS.'templates'.DS.$mainframe->getTemplate().DS.'css'.DS.$plugin->name.".css"))
		JHTML::stylesheet('templates/'.$mainframe->getTemplate().'/css/'.$plugin->name.".css");
	} 
}

class Plg_comment_storage {
	var $_comments = array();
	var $_commentsID = array();
	
	function &getInstance () {
		static $instance = null;
		
		if ($instance == null){ 
			$instance = new Plg_comment_storage();
		}
		
		return $instance;
	}
}

?>